package com.irate.dao;

import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.webkit.MimeTypeMap;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.irate.activity.R;
import com.irate.http.AsyncHttpClient;
import com.irate.http.AsyncHttpResponseHandler;
import com.irate.http.RequestParams;
import com.irate.model.RatingCategory;
import com.irate.model.RatingCriteria;
import com.irate.model.RatingDetailType;
import com.irate.provider.Constant;
import com.irate.provider.ContentManager;
import com.irate.service.AsyncHTTPRest;

public class RatingCategoryDAO {

	protected Random rand = new Random();

	public List<RatingDetailType> parseDetail(String str) {

		// //////////////
		RatingDetailType rdtsubfield01 = new RatingDetailType();
		rdtsubfield01.setTitle("Establishment's Name");
		rdtsubfield01.setHint("Type here");

		RatingDetailType rdtsubfield02 = new RatingDetailType();
		rdtsubfield02.setTitle("Establishment's Location");
		rdtsubfield02
				.setHint("Type here or type \"My Location\" for current position");

		List<RatingDetailType> details = new ArrayList<RatingDetailType>();
		details.add(rdtsubfield01);
		details.add(rdtsubfield02);

		// ///////////////
		RatingDetailType rdtsubfield001 = new RatingDetailType();
		rdtsubfield001.setTitle("xxxxxxxxxxxxxxxxxx");
		rdtsubfield001.setHint("Type here");

		RatingDetailType rdtsubfield002 = new RatingDetailType();
		rdtsubfield002.setTitle("yyyyyyyyyyyyyyyyyyy");
		rdtsubfield002
				.setHint("Type here or type \"My Location\" for current position");

		List<RatingDetailType> details2 = new ArrayList<RatingDetailType>();
		details2.add(rdtsubfield001);
		details2.add(rdtsubfield002);

		return rand.nextInt(2) == 0 ? details : details2;
	}

	public List<RatingCategory> parseListData(String json) {

		List<RatingCategory> lrc = new ArrayList<RatingCategory>();
		try {
			JSONObject obj = new JSONObject(json);
			JSONArray categoryArray = (JSONArray) obj.getJSONArray("message");

			for (int i = 0; i < categoryArray.length(); i++) {
				RatingCategory rc = getData(categoryArray.getString(i));

				lrc.add(rc);
			}
		} catch (Exception e) {

		}
		return lrc;
	}

	public RatingCategory getData(String str) throws JSONException {
		JSONObject rat_obj = new JSONObject(str);
		RatingCategory rc = new RatingCategory();

		rc.setCategory_id(rat_obj.getString("category_id"));
		rc.setCategory_name(rat_obj.getString("category_name"));

		List<RatingDetailType> lrdt = new ArrayList<RatingDetailType>();
		RatingDetailType rdt = new RatingDetailType();
		RatingDetailType rdt2 = new RatingDetailType();

		String sub1 = rat_obj.getString("category_sub1");
		String sub2 = rat_obj.getString("category_sub2");

		rdt.setTitle(sub1);
		rdt.setHint("Type \"" + sub1 + "\" here");
		rdt2.setTitle(sub2);
		rdt2.setHint("Type \"" + sub2 + "\" here");

		lrdt.add(rdt);
		lrdt.add(rdt2);

		rc.setListDetails(lrdt);
		return rc;
	}

	public void getListCategory(AsyncHttpResponseHandler handler,
			Context context, Dialog dialog) {

		ConnectivityManager con = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (con == null || con.getActiveNetworkInfo() == null
				|| !con.getActiveNetworkInfo().isConnected()) {

			Toast.makeText(
					context,
					context.getResources().getString(R.string.connection_error),
					Toast.LENGTH_LONG).show();

			if (dialog != null) {
				dialog.dismiss();
			}
		} else {
			String link = Constant.URL + "/"
					+ Constant.SERVICE_CATEGORY_CATEGORY_RATING + "/"
					+ Constant.SERVICE_GET;

			Header[] headers = { new BasicHeader("X-API-KEY", Constant.XAPIKEY) };

			AsyncHTTPRest.post(link, headers, null, handler);
		}
	}

	public void addNewCategory(AsyncHttpResponseHandler handler,
			Context context, String category, String subField1,
			String subField2, String criteria, String criteria_op1,
			String criteria_op2, Dialog dialog) {
		ConnectivityManager con = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (con == null || con.getActiveNetworkInfo() == null
				|| !con.getActiveNetworkInfo().isConnected()) {

			Toast.makeText(
					context,
					context.getResources().getString(R.string.connection_error),
					Toast.LENGTH_LONG).show();

			if (dialog != null) {
				dialog.dismiss();
			}

		} else {
			String link = Constant.URL + "/"
					+ Constant.SERVICE_CATEGORY_CATEGORY_RATING + "/"
					+ Constant.SERVICE_ADD;

			Header[] headers = { new BasicHeader("X-API-KEY", Constant.XAPIKEY) };

			RequestParams params = new RequestParams();
			params.add("cate_name", category);
			params.add("cate_sub1", subField1);
			params.add("cate_sub2", subField2);
			String str = criteria + "|" + criteria_op1 + "|" + criteria_op2;
			params.add("criteria_list", str);

			AsyncHTTPRest.post(link, headers, params, handler);
		}
	}

	public void upLoadPhoto(String path, PopupWindow view, Context context,
			ProgressDialog dialog) {
		ConnectivityManager con = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (con == null || con.getActiveNetworkInfo() == null
				|| !con.getActiveNetworkInfo().isConnected()) {

			if (dialog != null)
				dialog.dismiss();

			Toast.makeText(
					context,
					context.getResources().getString(R.string.connection_error),
					Toast.LENGTH_LONG).show();
		} else {
			String link = Constant.URL + "/" + Constant.SERVICE_IRATE + "/"
					+ Constant.SERVICE_UPLOAD_PHOTO;

			new FileUpload().execute(link, path, context, dialog, view);
		}
	}

	class FileUpload extends AsyncTask<Object, Void, String> {

		private PopupWindow pw;
		private Context context;
		private ProgressDialog dialog;

		@Override
		protected String doInBackground(Object... params) {

			pw = (PopupWindow) params[4];
			context = (Context) params[2];
			dialog = (ProgressDialog) params[3];

			String result = "";
			try {
				AsyncHttpClient asynHttpClient = AsyncHTTPRest
						.getAsynHttpClient();
				HttpClient httpClient = asynHttpClient.getHttpClient();

				HttpPost post = new HttpPost(new URI(params[0].toString()));
				File file = new File(params[1].toString());

				String extension = "";

				int i = file.getName().lastIndexOf('.');
				if (i > 0) {
					extension = file.getName().substring(i + 1);
				}

				String mime_type = "";
				mime_type = MimeTypeMap.getSingleton()
						.getMimeTypeFromExtension(extension);

				HttpEntity httpEntity = MultipartEntityBuilder
						.create()
						.addBinaryBody("fileUpload", file,
								ContentType.create(mime_type), file.getName())
						.build();

				post.setEntity(httpEntity);
				post.addHeader("X-API-KEY", "12345-67890");

				HttpResponse response = httpClient.execute(post);
				result = EntityUtils.toString(response.getEntity());
				dialog.dismiss();

			} catch (Exception e) {
				e.printStackTrace();
				String str = e.toString();
				System.out.print(str);
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);

			try {
				JSONObject obj = new JSONObject(result);

				if (obj.getString("return").toString().equals("true")) {

					ContentManager.getInstance().setFilePathRating(
							obj.getString("message"));

					Toast.makeText(context, "Upload success",
							Toast.LENGTH_SHORT).show();
					pw.dismiss();

				} else {
					Toast.makeText(context,
							obj.getString("message").toString(),
							Toast.LENGTH_SHORT).show();
				}

			} catch (Exception ex) {

			}

		}
	}

	public void submitRating(AsyncHttpResponseHandler handler, Context context,
			String cate_sub1, String cate_sub2, String privacy,
			String fb_share, Dialog dialog) {

		ConnectivityManager con = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (con == null || con.getActiveNetworkInfo() == null
				|| !con.getActiveNetworkInfo().isConnected()) {

			Toast.makeText(
					context,
					context.getResources().getString(R.string.connection_error),
					Toast.LENGTH_LONG).show();

			if (dialog != null) {
				dialog.dismiss();
			}
		} else {
			String link = Constant.URL + "/" + Constant.SERVICE_IRATE + "/"
					+ Constant.SERVICE_SUBMIT;

			RequestParams params = new RequestParams();
			ContentManager cm = ContentManager.getInstance();

			JSONObject objCriteria = getCriteria();

			params.put("cate_id", cm.getRating_category().getCategory_id());
			params.put("criteria", objCriteria.toString());
			params.put("comment", cm.getCommentContent());
			params.put("photo_path", cm.getFilePathRating());
			params.put("cate_sub1", cate_sub1);
			params.put("cate_sub2", cate_sub2);
			params.put("Privacy", privacy);
			params.put("FB_share", fb_share);
			Header[] headers = { new BasicHeader("X-API-KEY", Constant.XAPIKEY) };

			AsyncHTTPRest.post(link, headers, params, handler);
		}
	}

	private JSONObject getCriteria() {

		ContentManager cm = ContentManager.getInstance();
		JSONObject json = new JSONObject();

		for (int i = 0; i < cm.getListRatingCriteria().size(); i++) {
			RatingCriteria rc = cm.getListRatingCriteria().get(i);
			if (rc.getRate() > 0) {
				String name = rc.getName();
				String value = rc.getRate() + "";

				try {

					json.put(name, value);

				} catch (Exception e) {

				}

			}
		}

		return json;
	}

	public Boolean checkCriteria() {
		ContentManager cm = ContentManager.getInstance();

		for (int i = 0; i < cm.getListRatingCriteria().size(); i++) {

			RatingCriteria rc = cm.getListRatingCriteria().get(i);
			if (rc.getRate() > 0)
				return true;
		}
		return false;
	}
}
